//
//  SpinnerView.swift
//  CustomScrollview
//
//  Created by Apple on 2018/3/4.
//  Copyright © 2018年 Apple. All rights reserved.
//

import UIKit
public let TextColor = UIColor.DeepBlack
public let BorderColor = UIColor.white.cgColor

protocol SpinnerViewClick{
    func itemclick(_ index:Int)
}

class SpinnerView: UIView {
    var titlelist = [String]()
    var rowHeight:CGFloat = 0.0
    let cellStr = "cell"
    var tableViewHeight:CGFloat = 0.0
    let timeInterval = 0.25
    var isshow = false
    var delegate:TypeClick?
    var btnClick:NormalClick?
    
    var maxItem = 5
    
    lazy var select:UIButton = {
        let btn = UIButton(type: UIButtonType.custom)
        btn.setTitle("请选择", for: .normal)
        btn.setTitleColor(TextColor, for: .normal)
        btn.contentHorizontalAlignment = .left
        btn.contentVerticalAlignment = .center
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0)
        btn.layer.borderWidth = 1.0
        btn.layer.borderColor = BorderColor
        btn.isSelected = false
        btn.titleLabel?.font = UIFont(name: "AppleGothic", size: 15.0)
        btn.addTarget(self, action: #selector(showorhideMenu(_:)), for: UIControlEvents.touchUpInside)
        return btn
    }()
    
    lazy var tableview:UITableView = {
        var view = UITableView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: 0.0))
        view.dataSource = self
        view.delegate = self
        view.isScrollEnabled=true
        view.separatorStyle = UITableViewCellSeparatorStyle.singleLine
        view.register(UITableViewCell.self, forCellReuseIdentifier: self.cellStr)
        view.bounces = false
        return view
        
    }()
    lazy var listview:UIView = {
        var view = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: 0.0))
        view.backgroundColor = UIColor.white
        view.isUserInteractionEnabled = true
        return view
    }()
    
    var left:NSLayoutConstraint?
    var top:NSLayoutConstraint?
    var right:NSLayoutConstraint?
    var height:NSLayoutConstraint?
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.rowHeight = 0
        initView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.rowHeight = 0
        initView()
    }
    
    convenience init(frame: CGRect,_title title:[String],_rowHeight rowHeight:CGFloat) {
        self.init(frame: frame)
        self.titlelist.append(contentsOf: title)
        self.rowHeight = rowHeight
        initView()
    }
    
    
    func setTitleList(_ title:[String],_rowHeight rowHeight:CGFloat){
        self.titlelist.append(contentsOf: title)
        self.rowHeight = rowHeight
        self.tableview.reloadData()
    }
    
    
    func initView(){
        self.addSubview(self.select)
        initConstraint()
    }
    
    func initConstraint() {
        /*self.tableview.translatesAutoresizingMaskIntoConstraints = false
         self.listview.translatesAutoresizingMaskIntoConstraints = false
         self.left = NSLayoutConstraint(item: self.tableview, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self.listview, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 0)
         self.top = NSLayoutConstraint(item: self.tableview, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.listview, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0)
         self.right = NSLayoutConstraint(item: self.tableview, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self.listview, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: 0)
         self.height = NSLayoutConstraint(item: self.tableview, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: self.tableViewHeight)
         self.listview.addConstraint(self.left!)
         self.listview.addConstraint(self.top!)
         self.listview.addConstraint(self.right!)
         self.tableview.addConstraint(self.height!)*/
        self.select.snp.updateConstraints({ (make) in
            make.left.equalTo(self.snp.left)
            make.top.equalTo(self.snp.top)
            make.bottom.equalTo(self.snp.bottom)
            make.right.equalTo(self.snp.right)
        })
    }
    override func layoutSubviews() {
        if self.listview.subviews.count>0{
            
        }else{
            self.listview.addSubview(self.tableview)
            self.superview?.superview!.addSubview(self.listview)
            self.listview.snp.updateConstraints({ (make) in
                make.top.equalTo(self.snp.bottom)
                make.left.equalTo(self.snp.left)
                make.right.equalTo(self.snp.right)
                make.height.equalTo(self.tableViewHeight)
                
            })
            self.tableview.snp.updateConstraints({ (make) in
                make.top.equalTo(self.listview.snp.top)
                make.left.equalTo(self.listview.snp.left)
                make.right.equalTo(self.listview.snp.right)
                make.height.equalTo(self.tableViewHeight)
            })
        }
    }
    
    func setSelectSection(_ selectPosition:Int){
        self.select.setTitle(self.titlelist[selectPosition], for: .normal)
    }
    
    func close(){
        if isshow{
            self.tableViewHeight = 0.0
            //self.isshow = false
            self.listview.snp.updateConstraints { (make) in
                make.height.equalTo(self.tableViewHeight)
            }
            self.tableview.snp.updateConstraints { (make) in
                make.height.equalTo(self.tableViewHeight)
            }
            
            UIView.animate(withDuration: timeInterval, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
                
                UIApplication.shared.keyWindow?.subviews.last?.layoutIfNeeded()
                
                
            }) { (complete) in
                if complete {
                    self.isshow = false
                }
                
            }
            
        }
    }
    
    func setStatus(){
        //var viewcontroller = getCurrentController()
        if isshow{
            self.tableViewHeight = 0.0
        }else{
            if self.maxItem > self.titlelist.count{
                self.tableViewHeight = CGFloat(self.titlelist.count) * self.rowHeight
            }else{
                self.tableViewHeight = CGFloat(self.maxItem) * self.rowHeight
            }
            //self.listview.superview?.superview!.bringSubview(toFront: self.listview)
            
        }
        //self.height?.constant = self.tableViewHeight
        self.listview.snp.updateConstraints { (make) in
            make.height.equalTo(self.tableViewHeight)
        }
        self.tableview.snp.updateConstraints { (make) in
            make.height.equalTo(self.tableViewHeight)
        }
        
        UIView.animate(withDuration: timeInterval, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
            
            UIApplication.shared.keyWindow?.subviews.last?.layoutIfNeeded()
            
            
        }) { (complete) in
            if complete {
                self.isshow = !self.isshow
            }
            
        }
        
    }
    
    @objc func showorhideMenu(_ btn:UIButton){
        setStatus()
        guard var t = self.btnClick else{
            return
        }
        t()
    }
    
    //获取当前的viewcontroller
    /*func getCurrentController() -> UIViewController{
        var currentController:UIViewController?
        while true {
            var nextResponder = self.superview?.next
            if nextResponder is UIViewController{
                currentController = nextResponder as! UIViewController
                break
            }
        }
        return (currentController ?? nil)!
    }*/
    
}

extension SpinnerView:UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return self.titlelist.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        var cell = tableview.dequeueReusableCell(withIdentifier: self.cellStr, for: indexPath)
        if cell == nil{
            cell = UITableViewCell(style: UITableViewCellStyle.value2, reuseIdentifier: self.cellStr)
        }
        cell.textLabel?.text = self.titlelist[indexPath.row]
        
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int{
        return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return self.rowHeight
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        setStatus()
        self.delegate?(indexPath.row)
        self.select.setTitle(titlelist[indexPath.row], for: .normal)
        self.isshow=true
        tableView.deselectRow(at: indexPath, animated: true)
        
    }
}

